﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Web.Helpers;
using System.Web.Helpers;
using System.IO;
using System.Web.Security;

namespace websitev2.Controllers
{
    public class ImageController : Controller
    {
        //
        // GET: /Image/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Upload(string ID)
        {
            // we need to know what kind of image we're uploading. 
            if (ID == null)
            {
                Response.Redirect("/");
            }

            // Setup the variables
            string _typeOfUpload = ID.ToString().ToLower(); 
            // Change this to the referring URL 
            string _gobackTo = "/"; 

             // Do the avatar upload
            if (_typeOfUpload == "avatar")
            {
                if (Membership.GetUser() == null)
                {
                    Response.Redirect(_gobackTo);
                }
                ViewBag.Header = "Upload your avatar"; 
            }

            // App Upload, we check the session for the APP ID, if there isn't one.. then it's back to where we came from
            if (_typeOfUpload == "app")
            {
                if (Session["AppID"] == null)
                {
                    // The app isn't loaded so go back
                    Response.Redirect(_gobackTo);
                   
                }
                ViewBag.Header = "Upload the application box shot"; 
            }

            // We need to know what to upload, like an avatar or such like. 
            Session["imagetype"] = ID;
            // For now stick it in the session

            return View();
        }


        [HttpPost]
        public ActionResult Upload()
        {
            // So far this should just work for images. 
            var image = WebImage.GetImageFromRequest();
            var originalImage = image; 

            if (image != null)
            {
                #region Check valid extension
                // Check to make sure it's an image file
                string[] filesplit = image.FileName.Split('.');

                // We need to store the extension. 
                string _extension = ""; 

                if (filesplit.Length > 1)
                {
                    // take the last bit of it
                    _extension = filesplit[filesplit.Length-1].ToLower();
                    if ((_extension != "png") && (_extension != "jpeg") && (_extension != "jpg"))
                    {
                        // Error.
                        return View(); 
                    }
                }
                else
                {
                    // bounce out as this not a valid file. 
                    Response.Redirect("/");
                }
                #endregion 

                // Make sure we've not timed out and lost the image type
                if (Session["imagetype"] == null)
                {
                    // This is a session time out. 
                    Response.Redirect("/"); 
                }

                string _imageType = Session["imagetype"].ToString().ToLower();

                // Do the avatar upload
                if (_imageType == "avatar")
                {
                    #region upload avatar
                    // No user.
                    if (Membership.GetUser() == null)
                    {
                        Response.Redirect("/"); 
                    }
                  
                    if (Session["oLogged"]==null)
                    {
                        // Check for loggedf in user. 
                        Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;

                        // The user session isn't populated, this should be general. 
                        Models.User.LoggedIn oLogged = Core.UserCore.LoadLoggedInUserDetails(userGuid);
                        // Populate the user session.
                        Session["oLogged"] = oLogged; 
                    }

                    Models.User.LoggedIn oUser = (Models.User.LoggedIn) Session["oLogged"];

                    string _fileName = oUser.UserGUID.ToString(); 
                    

                    #region Save File
                    //image.Resize(70, ((70 * image.Height) / image.Width));
                    image.Resize(66,66);
                    // This is a bug in the web image code which is adding a black border. 
                    image.Crop(1, 1, 0, 0); 
                    //var filename = Path.GetFileName(image.FileName);
                    
                    image.Save(Path.Combine("~/Uploads/Images", _fileName+".medium"));
                    //_filename = Path.Combine("~/Uploads/Images", _filename);

                    // Write the image record to the db and link it with the user. 
                    Core.Image.WriteImageRecord(oUser.UserGUID, oUser.UserID, Path.Combine("~/Uploads/Images"), _fileName +".medium."+ _extension, 1, true); 
                   
                    image.Resize(33, 33);
                    image.Crop(1, 1, 0, 0); 
                    
                    //filename = Path.GetFileName(image.FileName);
                    image.Save(Path.Combine("~/Uploads/Images", _fileName+".small"));
                    // Write the image record to the db and link it with the user. 
                    Core.Image.WriteImageRecord(oUser.UserGUID, oUser.UserID, Path.Combine("~/Uploads/Images"), _fileName +".small." +_extension , 2,true ); 
                    
                    
                    
                    #endregion 

                    // flush the session
                    Session["imagetype"] = null;
                    #endregion 

                    // If it's all good then we should redirect back to the users profile. 
                    return RedirectToAction("user", "stats", new { id = oUser.UserName});
                }

                if (_imageType == "app")
                {
                    #region Upload App Box Shot
                    if (Session["AppID"] == null)
                    {
                        Response.Redirect("/"); 
                    }

                    Int64 _AppID = Int64.Parse(Session["appid"].ToString()); 
                    string _fileName = "app" + Session["AppID"].ToString();

                    //image.Resize(70, ((70 * image.Height) / image.Width));
                    image.Resize(240, ((240 * image.Height) / image.Width));
                    // This is a bug in the web image code which is adding a black border. 
                    image.Crop(1, 1, 0, 0);
                    //var filename = Path.GetFileName(image.FileName);

                    image.Save(Path.Combine("~/Uploads/AppImages", _fileName + ".large"));
                    //_filename = Path.Combine("~/Uploads/Images", _filename);

                    
                    Core.Image.WriteImageRecord( _AppID, Path.Combine("~/Uploads/AppImages"), _fileName + ".large."+_extension, 100, true);

                    //  relink for web request, incase we've done something with the ratio
                    image = originalImage; 
                    image.Save(Path.Combine("~/Uploads/AppImages", _fileName + ".original"));

                    image.Resize(66, 66);
                    image.Crop(1, 1, 0, 0);
                    image.Save(Path.Combine("~/Uploads/AppImages", _fileName + ".medium"));
                    Core.Image.WriteImageRecord(_AppID, Path.Combine("~/Uploads/AppImages"), _fileName + ".medium." + _extension, 101, true);

                    image.Resize(33, 33);
                    image.Crop(1, 1, 0, 0);
                    image.Save(Path.Combine("~/Uploads/AppImages", _fileName + ".small"));
                    Core.Image.WriteImageRecord(_AppID, Path.Combine("~/Uploads/AppImages"), _fileName + ".small." + _extension, 102, true);

                 
                    
                    // Flush this
                    Session["AppiID"] = null;
                    return RedirectToAction("app", "stats", new { id = _AppID.ToString() });

                    #endregion 
                }


            }


            return View();
        }

    }
}
